package com.itcoon.cloud.framework.ex;

import com.itcoon.cloud.framework.ex.errorcode.IServiceErrorCode;
import com.itcoon.cloud.framework.ex.exception.BaseServiceException;
import com.itcoon.cloud.framework.ex.exception.CommonSdkException;
import com.itcoon.cloud.framework.ex.exception.DefaultServiceException;
import com.itcoon.cloud.framework.ex.exception.PseudoException;
import org.springframework.http.HttpStatus;

public class AssertHandler implements Raiser {
    private final boolean predicate;

    public AssertHandler(boolean predicate) {
        this.predicate = predicate;
    }

    @Override
    public void raiseCommon(String localizedMessage, String... args) {
        if(!predicate){
            throw new CommonSdkException(localizedMessage, args);
        }
    }

    @Override
    public void raiseCommon(String localizedMessage, Throwable cause, String... args) {
        if(!predicate){
            throw new CommonSdkException(localizedMessage, cause, args);
        }
    }

    public <EX extends BaseServiceException, E extends IServiceErrorCode<EX>> void raise(E responseEnum, String... args){
        if(!predicate){
            EX ex =  responseEnum.newException(args);
            throw ex;
        }
    }

    public <EX extends BaseServiceException, E extends IServiceErrorCode<EX>> void raise(E responseEnum, Throwable cause, String... args){
        if(!predicate){
            throw responseEnum.newException(cause, args);
        }
    }

    public void raise(String localizedMsg, String... args){
        this.raise(localizedMsg, null, args);
    }

    public void raise(String localizedMsg, Throwable cause, String... args){
        if(!predicate){
            throw new DefaultServiceException(localizedMsg, cause, args);
        }
    }

    /**
     * 抛出假性异常
     * @param T 发生异常时返回的结果
     */
    public void raisePseudo(Object T){
        if(!predicate){
            throw new PseudoException(T);
        }
    }

    /**
     * 抛出假性异常
     * @param T 发生异常时返回的结果
     * @param status 发生异常时返回的网络状态码
     */
    public void raisePseudo(Object T, HttpStatus status){
        if(!predicate){
            throw new PseudoException(T, status);
        }
    }

    /**
     * 抛出假性异常
     * @param T 发生异常时返回的结果
     * @param status 发生异常时返回的网络状态码
     * @param cause 异常的原因
     */
    @Override
    public void raisePseudo(Object T, HttpStatus status, Throwable cause) {
        if(!predicate){
            throw new PseudoException(T, status, cause);
        }
    }


}
